<template>
  <h3>新增代办事项</h3>
  <input type="text" v-model="todoName" placeholder="输入代办事项" @keydown.enter="addTodo(newTodo(todoName))">
</template>

<script lang="ts">
import { defineComponent, computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { key } from '../store'
import type { Todo } from '../types'

export default defineComponent({
  name: '',
  setup () {
    const todoName = ref('')
    const store = useStore(key)
    const router = useRouter()
    const todos = computed(() => store.state.todos?.todos)

    const newTodo = (todoName: string): Todo => {
      return {
        id: todos.value?.length + 1,
        name: todoName,
        completed: false
      }
    }
    const addTodo = (todo: Todo): void => {
      store.commit('todos/addTodo', todo)
      todoName.value = ''
      // 跳转回列表页面
      router.push({ path: '/' })
    }
    return {
      todoName,
      addTodo,
      newTodo
    }
  }
})
</script>

<style lang="scss" scoped>

</style>